package com.sugon.controller;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.view.PoiBaseView;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import com.sugon.annotation.AutoLog;
import com.sugon.annotation.LimitSubmit;
import com.sugon.entity.MaterialBaseEntity;
import com.sugon.entity.MaterialRecordEntity;
import com.sugon.entity.SpareStorePosEntity;
import com.sugon.entity.ToolsStorePosEntity;
import com.sugon.modules.base.consts.BusModule;
import com.sugon.modules.base.consts.MaterialBaseType;
import com.sugon.modules.sys.service.INoticeManager;
import com.sugon.service.*;
import com.sugon.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 领料单详细Controller
 *
 * @author sugon
 * @date 2020-01-08 08:53:20
 */
@Controller
@RequestMapping("materialrecord")
public class MaterialRecordController {
    @Autowired
    private MaterialRecordService materialRecordService;
    @Autowired
    private MaterialBaseService materialBaseService;
    @Autowired
    private SpareStorePosService spareStorePosService;
    @Autowired
    private ToolsStorePosService toolsStorePosService;
    @Resource
    private SparePartSafeStockService safeStockService;
    @Resource
    private INoticeManager noticeManager;

    /**
     * 根据领料单获取库存信息
     */
    @RequestMapping("/list")
    @ResponseBody
    public R list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);
        List<MaterialRecordEntity> materialRecordList = materialRecordService.queryList(query);
        int total = materialRecordService.queryTotal(query);
        PageUtils pageUtil = new PageUtils(materialRecordList, total, query.getLimit(), query.getPage());
        return R.ok().put("page", pageUtil);
    }

    @AutoLog(value = "导出领料明细", busModule = BusModule.LLD)
    @RequestMapping("/exportData")
    @ResponseBody
    public void export(@RequestParam Map<String, Object> queryParam, ModelMap map, HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException {
        // Step.2 获取导出数据
        MapUtil.removeEmptyValue(queryParam);
        List<MaterialRecordEntity> materialRecordList = materialRecordService.queryList(queryParam);
        String title = "领料明细_" + DateUtil.today();
        ExportParams params = new ExportParams(title, "导出人:" + ShiroUtils.getUserRealName(), title);
        map.put(NormalExcelConstants.DATA_LIST, materialRecordList); // 数据集合
        map.put(NormalExcelConstants.CLASS, MaterialRecordEntity.class);//导出实体
        map.put(NormalExcelConstants.PARAMS, params);//参数
        map.put(NormalExcelConstants.FILE_NAME, "领料明细_" + DateUtil.today());//文件名称
        PoiBaseView.render(map, request, response, NormalExcelConstants.EASYPOI_EXCEL_VIEW);
    }

    /**
     * 根据领料单获取库存信息
     *
     * @param params
     * @return
     */
    @RequestMapping("/listByStore")
    @ResponseBody
    public R listByStore(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);
        List<Map<String, Object>> materialRecordList = materialRecordService.listByStore(query);
        int total = materialRecordService.listByStoreTotal(query);
        PageUtils pageUtil = new PageUtils(materialRecordList, total, query.getLimit(), query.getPage());
        return R.ok().put("page", pageUtil);
    }

    /**
     * 根据领料单获取备件库存信息
     *
     * @param params
     * @return
     */
    @RequestMapping("/listBySpareStore")
    @ResponseBody
    public R listBySpareStore(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);
        List<Map<String, Object>> materialRecordList = materialRecordService.listByStore(query);
        int total = materialRecordService.listByStoreTotal(query);
        PageUtils pageUtil = new PageUtils(materialRecordList, total, query.getLimit(), query.getPage());
        return R.ok().put("page", pageUtil);
    }

    /**
     * 根据领料单获取工装库存信息
     *
     * @param params
     * @return
     */
    @RequestMapping("/listByToolsStore")
    @ResponseBody
    public R listByToolsStore(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);
        List<Map<String, Object>> materialRecordList = materialRecordService.listByToolsStore(query);
        int total = materialRecordService.listByToolsStoreTotal(query);
        PageUtils pageUtil = new PageUtils(materialRecordList, total, query.getLimit(), query.getPage());
        return R.ok().put("page", pageUtil);
    }

    /**
     * 查看信息
     */
    @RequestMapping("/info/{id}")
    @ResponseBody
    public R info(@PathVariable("id") String id) {
        MaterialRecordEntity materialRecord = materialRecordService.queryObject(id);
        return R.ok().put("materialRecord", materialRecord);
    }

    /**
     * 添加领料明细
     */
    @AutoLog(value = "添加领料明细", busModule = BusModule.LLD)
    @LimitSubmit(key = "addMaterialDetail:%s")
    @RequestMapping("/save")
    @ResponseBody
    public R save(@RequestBody MaterialRecordEntity materialRecord) {
        // 领用数不得小于1
        int num = materialRecord.getNum();
        if (num < 1) {
            return R.error("备件领用数量不得小于1");
        }
        // 获取领料单ID
        String materialBaseId = materialRecord.getMaterial();
        MaterialBaseEntity materialBase = materialBaseService.queryObject(materialBaseId);
        if (materialBase == null) {
            return R.error("领料单不存在,请确认！");
        }
        // 根据领料单类别对对应库存实施锁定
        int type = materialBase.getType();
        if (type == MaterialBaseType.SPARE_PART) {
            // 校验库位是否存在
            SpareStorePosEntity spareStorePos = spareStorePosService.queryObject(materialRecord.getPostionId());
            if (spareStorePos == null) {
                return R.error("库位不存在，请确认");
            }
            // 校验可用库存是否可用
            int curStoreNum = spareStorePos.getStoreNum();
            int curLocNum = spareStorePos.getLocNum();
            if (curStoreNum - curLocNum < num) {
                return R.error("可领用库存不足，请更换！");
            }
        } else if (type == MaterialBaseType.TOOLS) {
            // 校验库位是否存在
            ToolsStorePosEntity toolsStorePos = toolsStorePosService.queryObject(materialRecord.getPostionId());
            if (toolsStorePos == null) {
                return R.error("库位不存在，请确认");
            }
            // 校验可用库存是否可用
            int curStoreNum = toolsStorePos.getStoreNum();
            int curLocNum = toolsStorePos.getLocNum();
            if (curStoreNum - curLocNum < num) {
                return R.error("可领用库存不足，请更换！");
            }
        }
        // 保存领料单详情
        int rows = materialRecordService.add(materialRecord);
        if (rows > 0) {
            // 根据领料单类别对对应库存实施锁定
            String positionId = materialRecord.getPostionId();
            if (type == MaterialBaseType.SPARE_PART) {
                spareStorePosService.lockStockNum(positionId, num);
            } else if (type == MaterialBaseType.TOOLS) {
                toolsStorePosService.lockStockNum(positionId, num);
            }
            return R.ok();
        } else {
            return R.error();
        }
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
//    @RequiresPermissions("materialrecord:update")
    @ResponseBody
    public R update(@RequestBody MaterialRecordEntity materialRecord) {
        materialRecordService.update(materialRecord);

        return R.ok();
    }

    /**
     * 删除
     */
    @AutoLog(value = "删除领料明细", busModule = BusModule.LLD)
    @RequestMapping("/delete")
//    @RequiresPermissions("materialrecord:delete")
    @ResponseBody
    public R delete(@RequestBody String[] ids) {
        if (ArrayUtil.isEmpty(ids)) {
            return R.error();
        }
        materialRecordService.deleteBatch(ids);
        return R.ok();
    }

    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAll")
    @ResponseBody
    public R queryAll(@RequestParam Map<String, Object> params) {

        List<MaterialRecordEntity> list = materialRecordService.queryList(params);

        return R.ok().put("list", list);
    }

    /**
     * 工单用料统计报表
     */
    @RequestMapping("/queryReport")
    @ResponseBody
    public R queryReport(@RequestParam Map<String, Object> params) {


        Map<String, Object> resultMap = new HashMap();
        List<MaterialRecordEntity> list = materialRecordService.queryReport(params);
        /**
         * 数量 --num
         */
        List numlist = new ArrayList();
        /**
         * 名称
         */
        List namelist = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            numlist.add(list.get(i).getSpareName());
            namelist.add(list.get(i).getNum());
        }
        resultMap.put("numlist", numlist);
        resultMap.put("namelist", namelist);

        return R.ok().put("list", resultMap);
    }


}
